package com.baibei.product.quotation;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baibei.basic.BasicRecyclerViewAdapter;
import com.baibei.ebec.quotation.QuotationManager;
import com.baibei.ebec.quotation.event.IQuotationEvent;
import com.baibei.ebec.sdk.ApiConstant;
import com.baibei.ebec.sdk.BuildConfig;
import com.baibei.model.Area;
import com.baibei.model.PercentInfo;
import com.baibei.model.QuotationInfo;
import com.baibei.model.RankingInfo;
import com.baibei.model.UserInfo;
import com.baibei.module.AppRouter;
import com.baibei.module.BasicFragment;
import com.baibei.product.R;
import com.baibei.product.R2;
import com.baibei.quotation.QuotationFilter;
import com.baibei.ui.AppUI;
import com.baibei.widget.OrderByTextView;
import com.blankj.utilcode.utils.ToastUtils;
import com.blankj.utilcode.utils.Utils;
import com.google.gson.Gson;
import com.rae.swift.session.SessionManager;
import com.rae.widget.RaePlaceHolderLayout;
import com.rae.widget.dialog.IDialogItemClickListener;
import com.rae.widget.dialog.impl.SingleFilterDialog;
import com.rae.widget.dialog.model.FilterParamsBean;

import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.umeng.socialize.utils.ContextUtil.getPackageName;

/**
 * 排行榜
 * Created by ChenRui on 2017/8/9 0009 14:28.
 */
public class RankingListFragment extends BasicFragment implements RankingListContract.View, OrderByTextView.OnOrderByChangedListener, BasicRecyclerViewAdapter.OnItemClickListener<RankingInfo>, IQuotationEvent {

    @BindView(R2.id.rec)
    RecyclerView mRecyclerView;
    @BindView(R2.id.tv_share)
    TextView tvShare;
    Unbinder unbinder;
    @BindView(R2.id.tv_guide)
    TextView tvGuide;
    //    @BindView(R2.id.tv_copper_red)
//    TextView tvCopperRed;
//    @BindView(R2.id.tv_copper_green)
//    TextView tvCopperGreen;
//    @BindView(R2.id.tv_copper_up)
//    TextView tvCopperUp;
//    @BindView(R2.id.tv_copper_down)
//    TextView tvCopperDown;
//    @BindView(R2.id.tv_silver_red)
//    TextView tvSilverRed;
//    @BindView(R2.id.tv_silver_green)
//    TextView tvSilverGreen;
//    @BindView(R2.id.tv_silver_up)
//    TextView tvSilverUp;
//    @BindView(R2.id.tv_silver_down)
//    TextView tvSilverDown;
//    @BindView(R2.id.tv_gold_red)
//    TextView tvGoldRed;
//    @BindView(R2.id.tv_gold_green)
//    TextView tvGoldGreen;
//    @BindView(R2.id.tv_gold_up)
//    TextView tvGoldUp;
//    @BindView(R2.id.tv_gold_down)
//    TextView tvGoldDown;
//        @BindView(R2.id.tv_price_au)
//    TextView tvPriceAu;
//    @BindView(R2.id.tv_percent_au)
//    TextView tvPercentAu;
//    @BindView(R2.id.tv_price_ag)
//    TextView tvPriceAg;
//    @BindView(R2.id.tv_percent_ag)
//    TextView tvPercentAg;
//    @BindView(R2.id.tv_price_cu)
//    TextView tvPriceCu;
//    @BindView(R2.id.tv_percent_cu)
//    TextView tvPercentCu;
    @BindView(R2.id.cu_percent_up)
    TextView cuPercentUp;
    @BindView(R2.id.cu_red)
    View cuRed;
    @BindView(R2.id.cu_percent_down)
    TextView cuPercentDown;
    @BindView(R2.id.cu_green)
    View cuGreen;
    @BindView(R2.id.ag_percent_up)
    TextView agPercentUp;
    @BindView(R2.id.ag_red)
    View agRed;
    @BindView(R2.id.ag_percent_down)
    TextView agPercentDown;
    @BindView(R2.id.ag_green)
    View agGreen;
    @BindView(R2.id.au_percent_up)
    TextView auPercentUp;
    @BindView(R2.id.au_red)
    View auRed;
    @BindView(R2.id.au_percent_down)
    TextView auPercentDown;
    @BindView(R2.id.au_green)
    View auGreen;

    @BindView(R2.id.ptr)
    PtrFrameLayout mRefreshLayout;

    @BindView(R2.id.img_arrow)
    ImageView mArrowView;

    @BindView(R2.id.ll_filter_layout)
    View mFilterLayout;

    @BindView(R2.id.btn_area)
    TextView mFilterTextView;

    // 筛选对话框
    SingleFilterDialog mFilterDialog;

    @BindView(R2.id.btn_price)
    OrderByTextView mPriceOrderByView;

    @BindView(R2.id.btn_rose)
    OrderByTextView mRoseOrderByView;

    @BindView(R2.id.placeholder)
    RaePlaceHolderLayout mPlaceHolderLayout;
    @BindView(R2.id.btn_pay_price)
    OrderByTextView mPayPriceOrderByView;
    @BindView(R2.id.ll_rank)
    LinearLayout llRank;

    private RankingListContract.Presenter mPresenter;
    private SparseArray<QuotationInfo> mQuotations;
    private double closeCuPrice;
    private double closeAgPrice;
    private double closeAuPrice;
    private int buyColorResource;
    private int sellColorResource;
    private int neutralColorResource;
    private JSONObject qob1;
    private JSONObject qob2;
    private JSONObject qob3;
    private int cuProductId;
    private int agProductId;
    private int auProductId;
    private List<RankingInfo> rankingInfos;
    private RankingAdapter mAdapter;
    private boolean isRankVisible = true;

    public static RankingListFragment newInstance() {
        return new RankingListFragment();
    }

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.fm_product_quotation;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter = inject(RankingListContract.Presenter.class);
    }

    @Override
    public void onDestroy() {
        mAdapter.setOnItemClickListener(null);
        QuotationManager.getInstance().unregister(this);
        mPresenter.destroy();
        super.onDestroy();
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        mAdapter = new RankingAdapter(getContext());

        //获取伦敦金银铜的昨日关市价
        getLastPrice();


        buyColorResource = ResourcesCompat.getColor(Utils.getContext().getResources(), R.color.buyColor, null);
        sellColorResource = ResourcesCompat.getColor(Utils.getContext().getResources(), R.color.sellColor, null);
        neutralColorResource = ResourcesCompat.getColor(Utils.getContext().getResources(), R.color.textPrimary, null);

        // 注册行情
        QuotationFilter filter = new QuotationFilter(QuotationFilter.ACTION_QUOTATION_PRODUCT);
        QuotationManager.getInstance().register(this, filter);

        super.onViewCreated(view, savedInstanceState);
        mFilterDialog = new SingleFilterDialog(getContext());
        mFilterDialog.setArrowView(mArrowView);
        List<FilterParamsBean> data = new ArrayList<>();

        FilterParamsBean filterItem = new FilterParamsBean(Area.ALL.name(), "全部商品");
        data.add(filterItem);
        data.add(new FilterParamsBean(Area.XAU.name(), "黄金饰品"));
        data.add(new FilterParamsBean(Area.XAG.name(), "白银饰品"));
        data.add(new FilterParamsBean(Area.LMCADS03.name(), "铜饰品"));

        mFilterDialog.notifyDataSetChange(data);
        mFilterDialog.setSelectedItem(filterItem);
        mFilterDialog.setOnItemClickListener(new IDialogItemClickListener<FilterParamsBean>() {
            @Override
            public void onItemClick(View view, FilterParamsBean filterParamsBean, int i) {
                mFilterTextView.setText(filterParamsBean.getName());
                // 加载数据
                mRefreshLayout.autoRefresh();
            }
        });
        mAdapter.setOnItemClickListener(this);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mAdapter);
        mRefreshLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                mPresenter.start();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View view, View header) {
                return !mRecyclerView.canScrollVertically(-1);
            }
        });

        mPlaceHolderLayout.subscribe(mAdapter);
        mPriceOrderByView.setOnOrderByChangedListener(this);
        mRoseOrderByView.setOnOrderByChangedListener(this);
        mPayPriceOrderByView.setOnOrderByChangedListener(this);
    }

    private void getLastPrice() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = ApiConstant.API_BASE_URL + "cbclient/api/index";
                HashMap<String, Object> map = new HashMap<>();
                map.put("exchange", BuildConfig.EXCHANGE);
                map.put("requestId", UUID.randomUUID().toString());
                if (SessionManager.getDefault().getUser() != null) {
                    map.put("userId", ((UserInfo) SessionManager.getDefault().getUser()).getUserId() + "");
                } else {
                    map.put("userId", "0");
                }
                map.put("platform", "server");
                map.put("deviceId", "BB-" + System.currentTimeMillis() + "-" + UUID.randomUUID().toString());
                map.put("timestamp", "" + System.currentTimeMillis());
                map.put("version", getVersion());
                map.put("memberChannel", ApiConstant.MEMBER_CHANNEL);
                map.put("appKey", BuildConfig.APPKEY);
                Gson gson = new Gson();
                String s = gson.toJson(map);
                OkHttpClient client = new OkHttpClient();
                RequestBody requestBody = FormBody.create(MediaType.parse("applicaiton/json; charset=utf-8"), s);
                Request request = new Request.Builder()
                        .post(requestBody)
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    final JSONObject jsonObject = new JSONObject(response.body().string());
                    String code = jsonObject.optString("code");
                    if (!"SUCCESS".equals(code)) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showShortToast(jsonObject.optString("message"));
                            }
                        });
                        return;
                    }
                    JSONArray quotations = jsonObject.optJSONObject("data").optJSONArray("quotations");
                    qob1 = quotations.getJSONObject(0);
                    qob2 = quotations.getJSONObject(1);
                    qob3 = quotations.getJSONObject(2);

                    JSONObject cuob = whichOb("LMCADS03");
                    JSONObject agob = whichOb("XAG");
                    JSONObject auob = whichOb("XAU");

                    closeCuPrice = cuob.optDouble("closePrice");
                    closeAgPrice = agob.optDouble("closePrice");
                    closeAuPrice = auob.optDouble("closePrice");

                    cuProductId = cuob.optInt("productId");
                    agProductId = agob.optInt("productId");
                    auProductId = auob.optInt("productId");
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private JSONObject whichOb(String area) {
        if (area.equals(qob1.optString("area"))) {
            return qob1;
        } else if (area.equals(qob2.optString("area"))) {
            return qob2;
        } else if (area.equals(qob3.optString("area"))) {
            return qob3;
        }
        return null;
    }

    /**
     * 选择区域
     */
    @OnClick({R2.id.btn_area, R2.id.img_arrow})
    public void onAreaClick() {
        // 显示列表
        if (mFilterDialog.isShowing()) return;
        mFilterDialog.showAsDropDown(mFilterLayout, 0, 0);
    }

    /**
     * 最新价格点击
     */
    @OnClick(R2.id.btn_price)
    public void onPriceClick() {
//        View cView = mRecyclerView.getChildAt(2);
//        RankingViewHolder childViewHolder = (RankingViewHolder)
//                mRecyclerView
//                .getChildViewHolder(cView);
//        childViewHolder.performItemClick();
    }

    /**
     * 涨跌幅点击
     */
    @OnClick(R2.id.btn_rose)
    public void onRoseClick() {

    }

    /**
     * 订金点击
     */
    @OnClick(R2.id.btn_pay_price)
    public void onPayPriceClick() {
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mRefreshLayout.autoRefresh();
    }

    /**
     * 获取区域
     */
    @Override
    public Area getArea() {
        FilterParamsBean selectedItem = mFilterDialog.getSelectedItem();
        if (selectedItem == null) return Area.ALL;
        return Area.typeOf(selectedItem.getId());
    }

    /**
     * 获取价格排序方式
     */
    @Override
    public String getPriceOrderBy() {
        return mPriceOrderByView.getOrderBy().name();
    }

    /**
     * 获取涨幅的排序方式
     */
    @Override
    public String getRoseOrderBy() {
        return mRoseOrderByView.getOrderBy().name();
    }

    /**
     * 获取订金的排序方式
     */
    @Override
    public String getPayPriceOrderBy() {
        return mPayPriceOrderByView.getOrderBy().name();
    }

    @Override
    public void onLoadDataFailed(String msg) {
        mRefreshLayout.refreshComplete();
        AppUI.failed(getContext(), msg);
    }

    @Override
    public void onLoadDataSuccess(List<RankingInfo> rankingInfoList) {
        mRefreshLayout.refreshComplete();
        rankingInfos = rankingInfoList;
        mAdapter.setDataList(rankingInfoList);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onLoadPercentFailed(String msg) {

    }

    /**
     * 订购比例获取
     */
    @Override
    public void onLoadPercentSuccess(PercentInfo percentInfo) {

        agPercentUp.setText(percentInfo.getBYXJ() + "%");
        agPercentDown.setText(percentInfo.getBYJSJ() + "%");
        auPercentUp.setText(percentInfo.getHJXJ() + "%");
        auPercentDown.setText(percentInfo.getHJJSJ() + "%");
        cuPercentUp.setText(percentInfo.getTXJ() + "%");
        cuPercentDown.setText(percentInfo.getTJSJ() + "%");

        agRed.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, percentInfo.getBYXJ()));
        agGreen.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, percentInfo.getBYJSJ()));
        auRed.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, percentInfo.getHJXJ()));
        auGreen.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, percentInfo.getHJJSJ()));
        cuRed.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, percentInfo.getTXJ()));
        cuGreen.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, percentInfo.getTJSJ()));

    }

    @Override
    public void onOrderByChanged(OrderByTextView view, OrderByTextView.OrderBy value) {
        // 价格排序
        if (view == mPriceOrderByView) {
            mRoseOrderByView.setOrderBy(OrderByTextView.OrderBy.DEFAULT);
            mPayPriceOrderByView.setOrderBy(OrderByTextView.OrderBy.DEFAULT);
        }
        if (view == mRoseOrderByView) {
            mPriceOrderByView.setOrderBy(OrderByTextView.OrderBy.DEFAULT);
            mPayPriceOrderByView.setOrderBy(OrderByTextView.OrderBy.DEFAULT);
        }
        if (view == mPayPriceOrderByView) {
            mRoseOrderByView.setOrderBy(OrderByTextView.OrderBy.DEFAULT);
            mPriceOrderByView.setOrderBy(OrderByTextView.OrderBy.DEFAULT);
        }

        mPresenter.refresh();
    }

    @Override
    public void onItemClick(View view, int i, RankingInfo item) {
        AppRouter.routeToTrade(getContext(), item.getEstimateTime(), item, item.getSaleTips());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R2.id.tv_share)
    public void onShareClicked() {
//        SessionManager sm = SessionManager.getDefault();
//        if (!sm.isLogin()) {
//            AppRouter.routeToLogin(getActivity());
//            return;
//        }
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                getShareUrl();
//            }
//        }).start();
//        View cView = mRecyclerView.getChildAt(3);
//        RankingViewHolder childViewHolder = (RankingViewHolder)
//                mRecyclerView
//                        .getChildViewHolder(cView);
//        childViewHolder.performItemClick();
    }

    private void getShareUrl() {
        String url = ApiConstant.API_BASE_URL + "yq/invi";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = client.newCall(request);
        try {
            Response response = call.execute();
            JSONObject jsonObject = new JSONObject(response.body().string());
            String state = jsonObject.optString("code");
            if (!"SUCCESS".equals(state)) {
                Toast.makeText(getContext(), "打开分享失败，请检查后重新尝试", Toast.LENGTH_LONG).show();
                return;
            }
            JSONObject job = jsonObject.optJSONObject("data");
            String shareUrl = job.optString("url");
            toShareUrl(shareUrl);
        } catch (IOException e) {
            Toast.makeText(getContext(), "网络异常，请检查后重试", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void toShareUrl(String url) {
        AppRouter.routeToWeb(getContext(), url);
    }

    @OnClick(R2.id.tv_guide)
    public void onGuideClicked() {
        AppRouter.routeToNewhand(getContext());
    }

    @Override
    @Subscribe
    public void onEvent(SparseArray<QuotationInfo> quotations) {
        mQuotations = quotations;
        refresh();
    }

    private void refresh() {
        if (closeCuPrice == 0 || (closeAgPrice == 0 || closeAuPrice == 0)) {
            return;
        }
        if (mQuotations.get(cuProductId) == null || (mQuotations.get(agProductId) == null || mQuotations.get(auProductId) == null)) {
            return;
        }
        double marketAuPrice = mQuotations.get(auProductId).getMarketPrice();
        double marketAgPrice = mQuotations.get(agProductId).getMarketPrice();
        double marketCuPrice = mQuotations.get(cuProductId).getMarketPrice();

//        //价格
//        tvPriceAu.setText(marketAuPrice + "");
//        tvPriceAg.setText(marketAgPrice + "");
//        tvPriceCu.setText(marketCuPrice + "");
//
//        //价格颜色
//        tvPriceAu.setTextColor(marketAuPrice > closeAuPrice ? buyColorResource : (marketAuPrice == closeAuPrice ? neutralColorResource : sellColorResource));
//        tvPriceAg.setTextColor(marketAgPrice > closeAgPrice ? buyColorResource : (marketAgPrice == closeAgPrice ? neutralColorResource : sellColorResource));
//        tvPriceCu.setTextColor(marketCuPrice > closeCuPrice ? buyColorResource : (marketCuPrice == closeCuPrice ? neutralColorResource : sellColorResource));
//        //涨跌幅背景色
//        tvPercentAu.setBackgroundResource(marketAuPrice > closeAuPrice ? R.drawable.btn_trade_up : (marketAuPrice == closeAuPrice ? R.drawable.btn_trade_neutral : R.drawable.btn_trade_down));
//        tvPercentAg.setBackgroundResource(marketAgPrice > closeAgPrice ? R.drawable.btn_trade_up : (marketAgPrice == closeAgPrice ? R.drawable.btn_trade_neutral : R.drawable.btn_trade_down));
//        tvPercentCu.setBackgroundResource(marketCuPrice > closeCuPrice ? R.drawable.btn_trade_up : (marketCuPrice == closeCuPrice ? R.drawable.btn_trade_neutral : R.drawable.btn_trade_down));
//        //涨跌幅
//        tvPercentAu.setText((marketAuPrice > closeAuPrice ? "+" : "") + (new BigDecimal(((marketAuPrice * 1.0f - closeAuPrice * 1.0f) / closeAuPrice * 1.0f) * 100).setScale(2, RoundingMode.DOWN) + "%"));
//        tvPercentAg.setText((marketAgPrice > closeAgPrice ? "+" : "") + (new BigDecimal(((marketAgPrice * 1.0f - closeAgPrice * 1.0f) / closeAgPrice * 1.0f) * 100).setScale(2, RoundingMode.DOWN) + "%"));
//        tvPercentCu.setText((marketCuPrice > closeCuPrice ? "+" : "") + (new BigDecimal(((marketCuPrice * 1.0f - closeCuPrice * 1.0f) / closeCuPrice * 1.0f) * 100).setScale(2, RoundingMode.DOWN) + "%"));
    }

    private String getVersion() {
        try {
            return getContext().getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "1.0.0";
        }
    }


}
